package org.basis.netty.c5;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.Scanner;

/**
 * echo客户端
 *
 * @author Mr_wenpan@163.com 2021/09/18 17:54
 */
@Slf4j
public class EchoClient {

    public static void main(String[] args) throws InterruptedException {

        NioEventLoopGroup group = new NioEventLoopGroup(1);

        Channel channel = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    // 连接建立后为channel添加handler
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {

                        ChannelPipeline pipeline = ch.pipeline();

                        // StringEncoder继承ChannelOutboundHandlerAdapter，所以说是出站handler，负责将出站的消息转换为string
                        pipeline.addLast(new StringEncoder());

                        // 入站消息handler，负责接收消息
                        pipeline.addLast(new ChannelInboundHandlerAdapter() {
                            // 添加自定义的handler
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf byteBuf = (ByteBuf) msg;
                                System.out.println(byteBuf.toString(Charset.defaultCharset()));
                                // 数据不用再向下传递了
//                                super.channelRead(ctx, msg);

                                // 思考：这里需要释放buffer吗？
                            }
                        });

                    }
                }).connect(new InetSocketAddress("localhost", 8080))
                .sync()
                .channel();

        // channel关闭的future
        ChannelFuture closeFuture = channel.closeFuture();

        new Thread(() -> {
            // 读取控制台输入消息
            Scanner scanner = new Scanner(System.in);

            while (true) {
                String str = scanner.nextLine();
                if ("q".equals(str)) {
                    // 关闭通道
                    channel.close();
                    break;
                }
                channel.writeAndFlush(str);
            }

            closeFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    // channel关闭后优雅的关闭NioEventLoopGroup（NioEventLoopGroup相当于线程池）
                    group.shutdownGracefully();
                }
            });

        }).start();

    }
}
